/**   
* @Title: ImgJsonDecoderManager.java 
* @Package net.gdface.service.search 
* @Description: TODO 
* @author guyadong   
* @date 2015年5月15日 下午7:01:19 
* @version V1.0   
*/
package net.gdface.service.search;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JSON解码器管理器
 * @author guyadong
 *
 */
public class ImgJsonDecoderManager {
	private static final Logger logger = LoggerFactory.getLogger(ImgJsonDecoderManager.class);
	public static final ConcurrentMap <String,ImgJsonDecoder>decoders=new ConcurrentHashMap<String,ImgJsonDecoder>();
	private ImgJsonDecoderManager() {
	}

	/**
	 * 根据{@link JSONObject}中提供的类名(用{@link ImgJsonDecoder#KEY_DECODER}定义),<br>
	 * 返回解码器{@link ImgJsonDecoder}实例
	 * 
	 * @param jo
	 * @return {@link ImgJsonDecoder}实例
	 */
	public static final ImgJsonDecoder getJsonDecoder(JSONObject jo){
		if(decoders.isEmpty()){
			decoders.putIfAbsent(ImgJsonDecoder.BAIDU.getClass().getName(), ImgJsonDecoder.BAIDU);
			decoders.putIfAbsent(ImgJsonDecoder.SO360.getClass().getName(), ImgJsonDecoder.SO360);
		}
		try {
			String decoder=jo.getString(ImgJsonDecoder.KEY_DECODER);
			assert decoder != null && !decoder.isEmpty();
			if(decoders.containsKey(decoder)){
				return decoders.get(decoder);
			}else{
				Class<?> clazz = Class.forName(decoder);
				ImgJsonDecoder newDecoder=(ImgJsonDecoder) clazz.newInstance();
				ImgJsonDecoder oldDecoder;
				if (null == (oldDecoder = decoders.putIfAbsent(decoder, newDecoder)))
					return newDecoder;
				else
					return oldDecoder;
			}
		} catch (Exception e) {
			logger.error(e.toString());
			throw new RuntimeException(e);
		}
	}

}
